/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pokemon.dao;

import com.pokemon.entities.Pokemon;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author xolsak1
 */
@Component
@Repository("PokemonDAOJpa")
public class PokemonDAOJpa implements PokemonDAO{

    @PersistenceContext
    private EntityManager em;

    public void setEm(EntityManager em) {
        this.em = em;
    }
    
    
    public void addPokemon(Pokemon pokemon) {
        if ((pokemon == null)|| (pokemon.getId() != null)) {
            throw new IllegalArgumentException("Pokemon must not be null and id must be null");
        }
        em.persist(pokemon);
    }

    
    public Pokemon getPokemon(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("Pokemon must not be null");
        }
        Pokemon pokemon = em.find(Pokemon.class, id);
        return pokemon;
    }

    
    public void updatePokemon(Pokemon pokemon) {
        if ((pokemon == null)|| (pokemon.getId() == null)) {
            throw new IllegalArgumentException("Pokemon must not be null and id must not be null");
        }
        
        em.merge(pokemon);
    }

    
    public void removePokemon(Pokemon pokemon) {
        if ((pokemon == null)|| (pokemon.getId() == null)) {
            throw new IllegalArgumentException("Pokemon must not be null and id must not be null");
        }
        Pokemon pokemonToRemove = em.find(Pokemon.class, pokemon.getId());
        em.remove(pokemonToRemove);
    }

    
    public List<Pokemon> getAllPokemons() {
        Query query = em.createQuery("SELECT e FROM Pokemon e");
        return (List<Pokemon>) query.getResultList();
    } 

    /* 
     * Without implementation. Just for backward compatibility.
     */
    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}
